package logic

import (
	"context"
	"encoding/json"
	"rent/model/mysql"
	"rent/model/redis"
	"rent/rentrpc/internal/svc"
	"rent/rentrpc/rentrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *rentrpc.ListRequest) (*rentrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var lists []mysql.Product
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	get := redis.Client.Get("list" + in.Produce)

	if get.Val() == "" {
		mysql.DB.Debug().Model(mysql.Product{}).Offset(int(offset)).Limit(int(in.Size)).Where("produce like ?", "%"+in.Produce+"%").Order("price desc").Find(&lists)
		marshal, _ := json.Marshal(&lists)
		redis.Client.Set("list"+in.Produce, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &lists)
	}

	var liststruct []*rentrpc.ListStruct

	for _, list := range lists {
		str := &rentrpc.ListStruct{
			Produce:     list.Produce,
			Description: list.Description,
			Price:       int64(list.Price),
			UserId:      int64(list.UserId),
		}
		liststruct = append(liststruct, str)
	}

	return &rentrpc.ListResponse{List: liststruct}, nil
}
